<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRoute } from 'vue-router'

interface Commodity {
  id: number
  commodityName: string
  commodityDescription: string
  image: string
  price: number
  quantity?: number // 用于购物车数量
}

const route = useRoute()
const commodities = ref<Commodity[]>([])
const loading = ref(false)
const error = ref('')

// base64 转换为图片URL
const convertBase64ToUrl = (base64String: string) => {
  if (!base64String) return ''
  if (base64String.startsWith('data:image')) {
    return base64String
  }
  return `data:image/png;base64,${base64String}`
}

const getCommodityList = async () => {
  loading.value = true
  error.value = ''

  try {
    const businessId = route.params.id
    console.log('路由参数 route.params:', route.params)
    console.log('商家ID businessId:', businessId)

    if (!businessId) {
      throw new Error('商家ID不存在')
    }

    const token = localStorage.getItem('token')
    if (!token) {
      throw new Error('请先登录')
    }

    const url = `http://localhost:8080/business/itemList?id=${businessId}`
    console.log('请求URL:', url)

    const response = await fetch(url, {
      headers: {
        'Authorization': token
      }
    })

    if (!response.ok) {
      throw new Error(`获取失败: ${response.status}`)
    }

    const data = await response.json()
    console.log('API返回的原始数据:', data)

    commodities.value = data.map((item: Commodity) => ({
      ...item,
      image: convertBase64ToUrl(item.image),
      quantity: 0
    }))
    console.log('处理后的商品数据:', commodities.value)

  } catch (err) {
    error.value = err instanceof Error ? err.message : '获取商品列表失败'
    console.error('获取商品列表失败:', err)
  } finally {
    loading.value = false
  }
}

// 增加商品数量
const increaseQuantity = (commodity: Commodity) => {
  if (commodity.quantity !== undefined) {
    commodity.quantity++
  }
}

// 减少商品数量
const decreaseQuantity = (commodity: Commodity) => {
  if (commodity.quantity !== undefined && commodity.quantity > 0) {
    commodity.quantity--
  }
}

onMounted(() => {
  getCommodityList()
})
</script>

<template>



  <div class="commodity-list pb-10">
    <div v-if="loading" class="text-center py-4">
      加载中...
    </div>

    <div v-else-if="error" class="text-center py-4 text-red-500">
      {{ error }}
    </div>

    <div v-else class="space-y-4">
      <div v-for="item in commodities"
           :key="item.id"
           class="flex p-4 border-b border-gray-100">
        <!-- 商品图片 -->
        <div class="relative w-20 h-20 mr-3">
          <img :src="item.image"
               :alt="item.commodityName"
               class="w-full h-full object-cover rounded">
        </div>

        <!-- 商品信息 -->
        <div class="flex-1">
          <h3 class="text-4 font-medium mb-1">{{ item.commodityName }}</h3>
          <div class="text-3 text-gray-500 mb-1">{{ item.commodityDescription }}</div>
          <div class="text-3 text-red-500">
            ¥{{ item.price }}
          </div>
        </div>

        <!-- 数量控制 -->
        <div class="flex items-center">
          <button
            @click="decreaseQuantity(item)"
            class="w-8 h-8 flex items-center justify-center text-gray-600"
            :class="{ 'opacity-50': !item.quantity }">
            <span class="text-xl">-</span>
          </button>
          <span class="w-8 text-center">{{ item.quantity || 0 }}</span>
          <button
            @click="increaseQuantity(item)"
            class="w-8 h-8 flex items-center justify-center text-blue-500">
            <span class="text-xl">+</span>
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.commodity-list {
  background: #fff;
}

button {
  background: none;
  border: none;
  outline: none;
  cursor: pointer;
}

button:disabled {
  cursor: not-allowed;
  opacity: 0.5;
}

.text-4 {
  font-size: 16px;
}

.text-3 {
  font-size: 14px;
}
</style>